﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Yelper.Phone
{
	public partial class LinkTextBlock : UserControl
	{
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(LinkTextBlock), new PropertyMetadata(new PropertyChangedCallback(LinkTextBlock.OnTextChanged)));
        public string Text {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            var linkTextBlock = d as LinkTextBlock;
            if (linkTextBlock != null)
                linkTextBlock.buildControl();
        } 

        private void buildControl() {
            WrapPanel.Children.Clear();
            foreach (var word in Text.Split(new string[] { " ", Environment.NewLine }, StringSplitOptions.None)) {
                if (Uri.IsWellFormedUriString(word, UriKind.Absolute)) {                    
                    WrapPanel.Children.Add(new HyperlinkButton { Content = word + " ", Style=Application.Current.Resources["HyperlinkButtonStyleWrapped"] as Style, TargetName = "_blank", NavigateUri = new Uri(word), FontSize = FontSize });                    
                } else {
                    WrapPanel.Children.Add(new TextBlock { Text =  word + " ", TextWrapping=TextWrapping.Wrap, FontSize = FontSize });                    
                }
            }
        }

		public LinkTextBlock() {
			// Required to initialize variables
			InitializeComponent();
		}

	}
}